//Like Aspect. Common DAO
const _ = require('lodash');
const uuidv4 = require('uuid/v4');
const fs = require('fs');
const foodItemModel = require('../../app/models/foodItems.json');

module.exports = {
    getFoodItemByName : getFoodItemByName,
    getFoodItemByProducer: getFoodItemByProducer,
    addFoodItem : addFoodItem,
    deleteFoodItemById : deleteFoodItemById,
    getFoodItemList : getFoodItemList
}

function getFoodItemByName(name, callback) {
    let result = null;
    _.forEach(foodItemModel, (item) => {
        if (_.isEqual(name, item.name)) {
            result = item;
        }
    })
    callback(null, result);
}

function getFoodItemByProducer(producer, callback) {
    let result = null;
    _.forEach(foodItemModel, (item) => {
        if (_.isEqual(producer, item.producer)) {
            result = item;
        }
    })
    callback(null, result);
}

//Add food item
function addFoodItem(item, callback) {
    item.itemId = uuidv4();
    foodItemModel.push(item);
    var jsonString = JSON.stringify(foodItemModel, null, 4);
    fs.writeFile("./app/models/foodItems.json", jsonString, (err) => {
        if (err) throw err
        console.log('add success!');
    });
    callback(null, item);
}

//Delete food item
function deleteFoodItemById(itemId, callback) {
    _.forEach(foodItemModel, (item,index) => {
        if (_.isEqual(item.itemId, itemId)) {
            foodItemModel.splice(index,1);
        }
    })

    var jsonString = JSON.stringify(foodItemModel, null, 4);
    fs.writeFile("./app/models/foodItems.json", jsonString, (err) => {
        if (err) throw err
        console.log('delete success!');
    });
    callback(null, true);
}

//Get List 
function getFoodItemList(callback){
    callback(null, foodItemModel);
}